import 'dart:io';

import 'package:date_format/date_format.dart';
import 'package:loggy/loggy.dart';

void quickTest() {
  // Call this as soon as possible (Above runApp)
  Loggy.initLoggy(
    logPrinter: const PrettyPrinter(),
  );

  logDebug('This is debug message');
  logInfo('This is info message');
  logWarning('This is warning message');
  logError('This is error message');
}

class LogFileOutput extends PrettyPrinter {
  late Directory logDir = Directory(".");
  File? logFile;

  @override
  Future<void> onLog(LogRecord record) async {
    final time = record.time.toIso8601String().split('T')[1];
    final callerFrame = record.callerFrame == null ? '-' : '(${record.callerFrame?.location})';
    final level = record.level.toString().replaceAll('Level.', '').toUpperCase().padRight(8);

    String l = '$time $level ${record.loggerName} ${record.message}  ${record.stackTrace ?? ''} $callerFrame\r\n';
    if (record.level.priority <= LogLevel.debug.priority) {
      return;
    }
    DateTime now = DateTime.now();
    const timeFormat = [yyyy, "_", mm, "_", dd, "_", HH, "_", nn];
    String format = formatDate(now, timeFormat);
    String format2 = formatDate(now.add(const Duration(minutes: -2)), timeFormat);
    logFile = File('${logDir.path}/logs/$format.txt');
    var exists = logFile?.existsSync();
    if (!exists!) {
      logFile?.createSync(recursive: true);
    }
    var f = File('${logDir.path}/logs/$format2.txt');
    print("${logFile?.absolute.path}");
    print("${f.absolute.path}");
    exists = f.existsSync();
    if (exists) {
      f.deleteSync(recursive: true);
    }
    logFile?.writeAsStringSync(l, mode: FileMode.append);
  }
}

void writeToFile() {
  Loggy.initLoggy(
    logPrinter: LogFileOutput(),
  );
  var i = 0;
  while (i < 100) {
    logDebug('This is debug message $i');
    sleep(const Duration(seconds: 1));
    logInfo('This is info message $i');
    sleep(const Duration(seconds: 1));
    logWarning('This is warning message $i');
    sleep(const Duration(seconds: 1));
    logError('This is error message $i');
    sleep(const Duration(seconds: 1));
    i++;
  }
}

void main() {
  writeToFile();
}
